#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
@Date   : 2019/12/02

"""
import logging
import coreapi
import coreschema
from mmonitor.models.mysql_db import UserModel
from .base import ViewBase
from mmonitor.utils.validator import is_uuid4
from mmonitor.common.vars import attack_msg
# from .auth import check_login
from django.http.response import JsonResponse


def check_login(func):
    def wrapper(func, request, *args, **kwargs):
        print(request.session.keys)
        print(request.session.get("user"))
        if 'user' not in request.session:
            d = {"code": 40, "msg": "还没登录", 'status': 'error'}
            return JsonResponse(d)
        else:
            return func(request, *args, **kwargs)

    return wrapper


class UserView(ViewBase):
    get_fields = (
        coreapi.Field(
            name='u_id',
            location='query',
            description=u'用户id',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
    )

    # @check_login
    def get(self, request):
        """
            查询单个用户信息用
        """
        u_id = request.session.get("user")
        if not u_id:
            return self.error_response("还没登录")
        if not is_uuid4(u_id):
            return self.error_response(attack_msg)
        res = UserModel.get_or_none(UserModel.user_id == u_id)
        if not res:
            return self.error_response("你要找的用户丢了，请确认下")
        res = res.to_dict()
        res.pop("password")
        res.pop("id")
        return self.ok_response(res)

    put_fields = (
        coreapi.Field(
            name='username',
            location='query',
            description=u'用户名',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='password',
            location='query',
            description=u'密码',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='email',
            location='query',
            description=u'邮箱',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='phone',
            location='query',
            description=u'手机号，可选',
            required=False,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
    )

    def put(self, request):
        """
            用户注册
            还需要做校验，发邮件激活

        """

        username = request.bget_string("username")
        password = request.bget_string("password")
        email = request.bget_string("email")
        phone = request.bget_int("phone")

        res = UserModel.get_or_none((UserModel.username == username) or (UserModel.email == email))
        if res:
            return self.error_response("用户名/邮箱已经存在了，麻烦重新换一个试试")
        d = {
            "username": username,
            "password": password,
            "email": email,
            "phone": phone
        }
        UserModel.create(**d)

        return self.ok_response(msg="注册成功")

    post_fields = (
        coreapi.Field(
            name='u_id',
            location='query',
            description=u'用户id',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='password',
            location='query',
            description=u'密码,可选，用户提交更改才需要',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='email',
            location='query',
            description=u'邮箱',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='phone',
            location='query',
            description=u'手机号，可选',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
    )

    def post(self, request):
        u_id = request.bget_string("u_id")
        name = request.bget_int("name", 0)
        phone = request.bget_int("phone", 0)
        email = request.bget_string("email", '')
        password1 = request.bget_string("password1", "")
        password2 = request.bget_string("password2", "")

        if u_id != request.session['user'] or not is_uuid4(u_id):
            return self.error_response(attack_msg)
        user = UserModel.get_or_none(UserModel.user_id == u_id)
        if not user:
            return self.error_response("用户丢了")

        if phone:
            user.phone = phone
        if email:
            user.email = email
        user.name = name
        if password2:
            if user.password != password1:
                return self.error_response("原来的密码错误")
            elif password2 == user.password:
                return self.error_response("新密码和老密码都一样的。。")
            user.password = password2
        user.save()

        return self.ok_response()

    def delete(self, request):

        return self.ok_response(msg='数据删除成功', data='操作成功')
